package service.impl;

import dao.MenuDao;
import dao.RoleDao;
import dao.UserDao;
import dao.impl.MenuDaoImpl;
import dao.impl.RoleDaoImpl;
import dao.impl.UserDaoImpl;
import model.Menu;
import model.Role;
import model.User;
import service.RoleService;
import service.UserService;

import java.util.ArrayList;
import java.util.List;

public class UserServiceImpl implements UserService {
    UserDao userDao = new UserDaoImpl();

    @Override
    public User login(String username, String password) {
        RoleDao roleDao = new RoleDaoImpl();
        User users = userDao.login(username, password);
        if (users == null) {
            return null;
        }
        //根据角色id查询角色信息(三表联查)
        Integer roleId = users.getRoleId();
        Role roleById = roleDao.findById(roleId);
        //菜单分级
        List<Menu> menus = roleById.getMenus();
        List<Menu> newMenuList = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getUpmenuId() == 0) {
                List<Menu> secondList = new ArrayList<>();
                for (Menu second : menus) {
                    if (second.getUpmenuId() == menu.getMenuId()) {
                        secondList.add(second);
                    }
                }
                menu.setSecondMenus(secondList);
                newMenuList.add(menu);
            }
        }
        roleById.setMenus(newMenuList);
        users.setRole(roleById);
        return users;
    }

    @Override
    public List<User> getUsers(int pageIndex, int pageSize) {
        return userDao.getUsers(pageIndex, pageSize);
    }

    @Override
    public int total() {
        return userDao.total();
    }

    @Override
    public int addUser(User user) {
        return userDao.addUser(user);
    }

    @Override
    public User getUserById(int userid) {
        return userDao.getUserById(userid);
    }

    @Override
    public int update(User user) {
        return userDao.updateUser(user);
    }

    @Override
    public int delete(int userid) {
        return userDao.deleteUser(userid);
    }
}
